<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
/**
 * RPC handler
 * 
 * Shared code for RPC handlers.
 */
abstract class escape_repositoryui_RpcHandler
{
	/**
	 * Repository instance.
	 * @var escape_repository_Repository
	 */
	public $repository;
	
	/**
	 * Repository UI instance.
	 * @var escape_repositoryui_RepositoryUi
	 */
	public $repositoryUi;
	
	public $contentType = 'application/json';
	//public $contentType = 'text/plain';
	
	/**
	 * Get an instance of a RPC handler by name. 
	 * @param escape_repository_Repository $repository Repository instance
	 * @param escape_repositoryui_RepositoryUi $repositoryUi Repository UI instance
	 * @param string $handlerName Name of the RPC handler
	 * @return escape_repositoryui_RpcHandler RPC handler
	 */
	public static function getHandler(&$repository, &$repositoryUi, $handlerName)
	{
		$handler = null;
		
		// check handler name, to prevent exploits 
		if(preg_match('/^\w+$/',$handlerName))
		{
			$handlerFileName = 'escape/repositoryui/rpc/' . $handlerName . '.php';
			$handlerClassName = 'escape_repositoryui_rpc_' . $handlerName;

			// don't show warnings (from non-existing handlers)
			$previousErrorLevel = error_reporting(E_ALL ^ E_WARNING);
			include_once($handlerFileName);
			error_reporting($previousErrorLevel);

			if(class_exists($handlerClassName))
			{
				$handler = new $handlerClassName();
				if(get_class($handler) !== $handlerClassName)
				{
					// specified class name and actual class name are not identical, possibly due to case mismatch
					$handler = null;
				}
				else
				{
					$handler->repository =& $repository;
					$handler->repositoryUi =& $repositoryUi;

					// set gadget mode
					$isGadget = $_REQUEST['gadget'] == true || $_REQUEST['gadget'] == '1';
					if($isGadget)
					{
						$repositoryUi->enableGadgetMode();
					}
				}
			}
		}
		
		return $handler;
	}

	public function startHandleRequest()
	{
		if(!preg_match('/html/i', $this->contentType))
		{
			ini_set('html_errors', 0);
		}
		
		error_reporting(E_ALL & ~E_NOTICE);

		// register a custom error handler, this won't catch fatal errors however
		set_error_handler(array("escape_repositoryui_RpcHandler", "errorHandler"), E_ALL & ~E_NOTICE);
		
		register_shutdown_function('ob_end_flush');
		
		ob_start();
		
		header("Content-Type: " . $this->contentType);
		
		try
		{
			$this->handleRequest();
		}
		catch (Exception $exception)
		{
			ob_clean();
			
			header('HTTP/1.1 500 Internal Server Error');
			
			$message = $exception->getMessage();
			
			if(!($exception instanceof escape_repositoryui_exception_Rpc))
			{
				if($this->repository->config['debug'])
				{
					$message = "System error: " . $message;
				}
				else
				{
					$message = "A system error occurred while processsing this request";
				}
			}
			
			if(preg_match('/html/i', $this->contentType))
			{
				print htmlspecialchars($message);
			}
			else
			{
				header("Content-Type: text/plain");
				print $message;
			}
		}
	}
	
	public abstract function handleRequest();
	
	/**
	 * Convert PHP errors to exceptions, should be registered using set_error_handler().
	 * @param integer $errno level of the error raised
	 * @param string $errstr error message
	 * @param string $errfile filename that the error was raised in
	 * @param integer $errline line number the error was raised at
	 * @param array $errcontext active symbol table at the point the error occurred.
	 */
	public static function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
	{
	    if(error_reporting() == 0)
	    {
	        // Error reporting is currently turned off or suppressed with @
	        return false;
	    }
		throw new escape_repositoryui_exception_PhpError($errstr, $errno, $errfile, $errline, $errcontext);
	}
}
